package com.keyou.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keyou.reggie.common.CommonConstants;
import com.keyou.reggie.common.ResultInfo;
import com.keyou.reggie.entity.Employee;
import com.keyou.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @Author: klq
 * @Date: 2023/1/9 18:30
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping(value = "/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    //HttpServletRequest request作用：如果登录成功，将员工对应的id存到session一份，这样想获取一份登录用户的信息就可以随时获取出来
    @PostMapping("/login")
    public ResultInfo<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.将页面提交的密码进行MD5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        //使用getOne：因为user_name字段有unique唯一约束，不会出现查询出多个结果
        Employee emp = employeeService.getOne(queryWrapper);

        //3.如果没有查询到则返回登录失败结果
        if (emp == null) {
            return ResultInfo.error("登录失败");
        }

        //4.密码比对，如果不一致则返回登录结果
        if (!emp.getPassword().equals(password)) {
            return ResultInfo.error("登录失败");
        }

        //5.查看员工状态，如果已为禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return ResultInfo.error("账号已禁用");
        }

        //6.登录成功，将员工id存入session并返回登录成功结果
        request.getSession().setAttribute(CommonConstants.SESSION_EMPLOYEE, emp.getId());
        return ResultInfo.success(emp);
    }

    /**
     * 员工退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public ResultInfo<String> logout(HttpServletRequest request) {
        //清理session中保存的当前登录员工的id
        request.getSession().removeAttribute(CommonConstants.SESSION_EMPLOYEE);
        return ResultInfo.success("退出成功");
    }

    /**
     * 添加员工
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public ResultInfo<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增的员工信息：{}", employee.toString());
        ////设置默认密码为123456，并采用MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));

        //有了公共字段填充，这里不需要单独写了
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        Long employeeId = (Long) request.getSession().getAttribute(CommonConstants.SESSION_EMPLOYEE);
        employee.setCreateUser(employeeId);
        employee.setUpdateUser(employeeId);*/

        //存入数据库
        employeeService.save(employee);
        return ResultInfo.success("添加员工成功");
    }

    /**
     * 查询员工信息（分页）
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public ResultInfo<Page> page(int page, int pageSize, String name) {
        log.info("查询员工信息：page={},pageSize={},name={}", page, pageSize, name);
        //构造分页插件
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件（name为空时，查询所有）
        queryWrapper.like(!(name == null || "".equals(name)), Employee::getName, name);
        //对查询结果根据修改时间降序处理
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, queryWrapper);

        return ResultInfo.success(pageInfo);
    }

    /**
     * 修改员工信息：
     * 问题的原因：
     * JS对Long型数据进行处理时丢失精度，导致提交的id和数据库中的id不一致。
     * 如何解决这个问题?
     * 我们可以在服务端给页面响应json数据时进行处理，将Long型数据统一转为String字符串
     *
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public ResultInfo<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("修改员工信息：{}", employee.toString());
        //获取线程id
        long id = Thread.currentThread().getId();
        log.info("update的线程id为：{}", id);
        employeeService.updateById(employee);
        return ResultInfo.success("员工信息修改成功");
    }

    /**
     * 根据ID查询员工详情信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultInfo<Employee> getEmployeeById(@PathVariable Long id) {
        log.info("根据id：{}，查询员工信息", id);
        Employee employee = employeeService.getById(id);
        if (null != employee) {
            return ResultInfo.success(employee);
        }
        return ResultInfo.error("未查询到该员工信息");
    }


}